home *** CD-ROM | disk | FTP | other *** search
/ MacWorld 1999 July / Macworld (1999-07).dmg / Shareware World / Info / For Developers / Mops 3.4.sea / Mops source / PPC source / cg1 < prev    next >
Text File  |  1999-01-14  |  37KB  |  1,125 lines

  1. marker m__cg1
  2.  
  3.  
  4. \                =========================================
  5. \                        POWERPC CODE GENERATOR
  6. \                =========================================
  7.  
  8.  
  9. \ NOTE:  all the technical documentation is at the end of this file, 
  10. \  after the endload.
  11.  
  12.  
  13.  
  14. true    constant    assertions?    
  15.             \ make it false when everything really works?!?
  16.  
  17. PPC?
  18. [IF]
  19. false    constant    debug?
  20. [ELSE]
  21. false    constant    debug?
  22. [THEN]
  23.  
  24. false    constant    64bit?
  25.  
  26.  
  27. \        =============== OPTIMIZATION FLAGS ===============
  28.  
  29. (*    it's useful to be able to turn these off, to find those
  30.     recalcitrant bugs - and in the case of range checking,
  31.     to be able to turn it off for speed-critical tested
  32.     code.  Or for floating multiply-add, someone might want to
  33.     turn it off to restore strict IEEE FP semantics.
  34.     
  35.     NOTE: the default for all these boolean values is TRUE.
  36.  
  37. *)
  38.  
  39. true    value        hoist?                    \ can we move ops out of loops if
  40.                                             \  they're invariant in the loop?
  41.  
  42. true    value        hoist_fetches?            \ can we move fetches to as early
  43.                                             \  as possible?
  44.  
  45. true    value        allow_match?            \ true if we can eliminate an op if
  46.                                             \  we find the result already in
  47.                                             \  a register.  Basically the same
  48.                                             \  as CSE (common subexpression 
  49.                                             \  elimination).
  50.  
  51. true    value        move_by_recompiling?    \ can we try to recompile an earlier
  52.                                             \  op to avoid a reg move?
  53.  
  54. true    value        optimize_leaf_calls?    \ do we use the fast calling sequence
  55.                                             \  for leaf definitions?
  56.  
  57. true    value        optimize_branches?        \ do we simplify branches over other
  58.                                             \  branches, branches to the next
  59.                                             \  instruction, etc.?
  60.  
  61. true    value        cascade?                \ do we combine ops into single
  62.                                             \  instructions where we can?
  63.  
  64. true    value        range_check?            \ do we range-check array accesses?
  65.  
  66. true    value        multiply-add?            \ do we cascade a floating multiply
  67.                                             \  followed by an add into a 
  68.                                             \  floating multiply-add instruction
  69.                                             \  (or one of its variants)?
  70.  
  71.  
  72. \        =============== FORWARD DEFNS ================
  73.  
  74. forward .G
  75. forward .F
  76. forward .C
  77. forward .GS
  78. forward .CS
  79. forward .AL
  80. forward .FAL
  81. forward .FR
  82. forward ZS
  83.  
  84.  
  85.  
  86. \            =============== OTHER GLOBALS ==============
  87.  
  88.     0    value        backstop_CDP
  89.     0    value        fetch_backstop
  90.     0    value        basic_block_start
  91.     0    value        loop_start
  92.  
  93.     0    value        max_called_#PL
  94.     0    value        max_called_#FPL
  95.  
  96. false    value        equalizing?
  97. false    value        eq_block_recompiling_move?
  98.  
  99. bytestring            eq_ranges
  100. bytestring            const_data
  101. bytestring            sv_const_data
  102.  
  103.  
  104. 0        constant    CR0
  105.  
  106. 4096    constant    sys_SP_framesize
  107.  
  108. 8        constant    FPcell
  109.  
  110. (* We don't move the stack pointers every time we push and pop something
  111.    - rather, we keep track of the accumulated offset here and only adjust
  112.    when we have to.
  113. *)
  114.  
  115. 0    value    STK_OFFSET    
  116. 0    value    FSTK_OFFSET
  117.  
  118.  
  119. \        =================    OD FIELD VALUES    ==================
  120.  
  121. \ Here we define various values for OD fields.  We generally use the same
  122. \ names as for the 68k code generator, although the values aren't all
  123. \ the same (which doesn't matter anyway).
  124.  
  125. \ Mode values:
  126.  
  127.  
  128. enum {  mdGPR mdBD mdAbs mdLit mdPC mdFPn  }
  129.  
  130. PPC? [IF] hexx [ELSE] hex [THEN]
  131.  
  132. \ Flag byte bits:
  133.  
  134. \ 0    constant    flExt        \ Sign extend
  135. 1    constant    fbExt
  136.  
  137. \ 1    constant    flFP        \ Floating operation
  138. \ 2    constant    fbFP
  139.  
  140. (*
  141. 2    constant    flLit        \ Floating Literal
  142. 4    constant    fbLit
  143.  
  144. 3    constant    flFCR        \ FPU constant ROM reference
  145. 8    constant    fbFCR
  146. *)
  147.  
  148.  
  149. \ Operation type values (opType):
  150.  
  151. \ 0 means empty, 1 to 7 mean not empty but unknown for some reason.
  152. \  So far we've only defined 1-3.
  153.  
  154. 1    constant    otUnknown        \ isn't empty, but we don't know anything about
  155.                                 \  the contents
  156. 2    constant    otUnkStored        \ ditto, but we've stored it and so might be
  157.                                 \  able to optimize a fetch from the same
  158.                                 \  location, even tho we don't know its type
  159. 3    constant    otUnkPulled        \ ditto, pulled from memory part of stack
  160.  
  161. 7    constant    otUnknownCodes    \ all codes less than or equal to this are
  162.                                 \  some kind of empty/unknown
  163.             
  164. 8    constant    otMove            \ reg move
  165.  
  166.  
  167. \ the following are also on the 68k, and in target compilation they
  168. \  dispatch to us from the 68k interpreter using these codes, so we 
  169. \  can't change them!
  170.  
  171. 12    constant    otMUL
  172. 13    constant    otDIV
  173. 14    constant    otUDIV
  174.  
  175. \ the following are PPC only:
  176.  
  177. 10    constant    otMULH            \ multiply high
  178. 11    constant    otUMULH            \ multiply high
  179. 16    constant    otAddc
  180. \ 17    constant    otAddic
  181. 17    constant    otAdde
  182. 18    constant    otAddze
  183. 19    constant    otAddme
  184.  
  185. 1A    constant    otSubfc
  186. \ 1C    constant    otSubfic
  187. 1B    constant    otSubfe
  188. 1C    constant    otSubfze
  189. 1D    constant    otSubfme
  190.  
  191. \ these following are also 68k codes, and can't change
  192.  
  193. 21    constant    otADD
  194. 22    constant    otSUB
  195. 23    constant    otAND
  196. 24    constant    otOR
  197. 25    constant    otXOR
  198. 26    constant    otCMP
  199. 27    constant    otUCMP            \ unsigned compare - PPC only
  200.  
  201. 28    constant    otNEG
  202. 29    constant    otNOT
  203.  
  204. 2A    constant    otShift
  205. 2B    constant    otShift&mask    \ PPC only
  206. 2C    constant    otTrap            \ ditto
  207.  
  208. 30    constant    otPMend            \ End of integer ops
  209.  
  210. \ 3F    constant    otFPcmp        \ Floating-point comparison.  A special case.
  211. 40    constant    otFPstart        \ Start of regular floating-point ops.  Note 
  212.                                 \  these are NOT in the same order as the 
  213.                                 \  integer ops.
  214. 40    constant    otFMOVE
  215. 41    constant    otFADD
  216. 42    constant    otFMUL
  217. 43    constant    otFMADD            \ multiply-add - PPC only
  218. 44    constant    otFNMSUB        \ negative multiply-subtract - AltiVec only
  219.  
  220. 48    constant    otFPnoncom        \ The following FP ops are non-commutative
  221.  
  222. 48    constant    otFSUB
  223. 49    constant    otFDIV
  224.  
  225. 4F    constant    otFPcmp            \ FP comparisons
  226.  
  227. 160    constant    otFPstore
  228. 162    constant    otFPfetch
  229.  
  230. 54    constant    otFPmon            \ The following FP ops are monadic
  231.  
  232. (*        we don't bother including these in the dictionary, but these
  233.         are the values:
  234.  
  235. 54    constant    otFABS
  236. 55    constant    otFNEG
  237. 56    constant    otFSIN
  238. 57    constant    otFCOS
  239. 58    constant    otFTAN
  240. 59    constant    otFATAN
  241. 5A    constant    otFSQRT
  242. *)
  243.  
  244. 5F    constant    otFPend            \ End of FP ops
  245.  
  246. 60    constant    otStore            \ Store
  247. 62    constant    otFetch            \ Direct fetch
  248.  
  249. \ otFetch
  250. \    constant    otAt            \ Indirect fetch - ends up being treated
  251.                                 \    the same
  252.  
  253. 62    constant    otDUP            \ Stack shuffling
  254. 63    constant    ot2DUP
  255. 64    constant    otDROP
  256. 65    constant    ot2DROP
  257. 66    constant    otSWAP
  258. 67    constant    otOVER
  259.  
  260. (*    again we don't bother including these in the dictionary, but 
  261.     these are the values:
  262.  
  263. 68    constant    otNIP
  264. 69    constant    otTUCK
  265. 6A    constant    otROT
  266. 6B    constant    otDOWN
  267. 6C    constant    ot2SWAP
  268.  
  269. For FP stack shuffling, we'll use the corresponding
  270.  opcodes in the range 72 - 7B.
  271.  
  272. We'll use opcodes in the range 80 - A0 for unique AltiVec ops like
  273. vector splat that have no scalar equivalents:
  274.  
  275. 80    vector splat
  276. 81    vector splat immediate
  277.  
  278. 90    vector select
  279. 91    vector permute
  280.  
  281. *)
  282.  
  283.  
  284. 200    constant    otVecOffset        \ all vector ops have this bit set so we
  285.                                 \  can recognize them quickly.
  286.  
  287.  
  288. \ Subtype byte values:
  289.  
  290. \ For comparisons, the top 4 bits of the byte give the condition register field
  291. \ bit which we need to branch on for this condition:  LT = 0, GT = 1, EQ = 2.
  292. \ The low bit (bit 7) is 1 if the condition we want has a field bit value of 1.
  293. \ Bit 6 is 1 for unsigned, and bit 5 is 1 for comparisons with zero.
  294.  
  295. 20    constant    cmpNE
  296. 21    constant    cmpEQ
  297. 00    constant    cmpGE
  298. 01    constant    cmpLT
  299. 10    constant    cmpLE
  300. 11    constant    cmpGT
  301. 02    constant    cmpHS
  302. 03    constant    cmpLO
  303. 12    constant    cmpLS
  304. 13    constant    cmpHI
  305.  
  306. 24    constant    cmpZNE
  307. 25    constant    cmpZEQ
  308. 04    constant    cmpZGE
  309. 05    constant    cmpZLT
  310. 14    constant    cmpZLE
  311. 15    constant    cmpZGT
  312.  
  313. \ here's a table to map our 68k comparison codes to the above PPC ones:
  314.  
  315. PPC? [IF]
  316.  
  317.   createx    comparison_codes
  318.     0        cx,        \ 0
  319.     0        cx,        \ 1
  320.     cmpHI    cx,        \ 2
  321.     cmpLS    cx,        \ 3
  322.     cmpHS    cx,        \ 4
  323.     cmpLO    cx,        \ 5
  324.     cmpNE    cx,        \ 6
  325.     cmpEQ    cx,        \ 7
  326.     0        cx,        \ 8
  327.     0        cx,        \ 9
  328.     0        cx,        \ A
  329.     0        cx,        \ B
  330.     cmpGE    cx,        \ C
  331.     cmpLT    cx,        \ D
  332.     cmpGT    cx,        \ E
  333.     cmpLE    cx,        \ F
  334.  
  335. decimalx
  336.  
  337. [ELSE]
  338.  
  339.   create comparison_codes
  340.  
  341.     0        c,        \ 0
  342.     0        c,        \ 1
  343.     cmpHI    c,        \ 2
  344.     cmpLS    c,        \ 3
  345.     cmpHS    c,        \ 4
  346.     cmpLO    c,        \ 5
  347.     cmpNE    c,        \ 6
  348.     cmpEQ    c,        \ 7
  349.     0        c,        \ 8
  350.     0        c,        \ 9
  351.     0        c,        \ A
  352.     0        c,        \ B
  353.     cmpGE    c,        \ C
  354.     cmpLT    c,        \ D
  355.     cmpGT    c,        \ E
  356.     cmpLE    c,        \ F
  357.  
  358. decimal
  359.  
  360. [THEN]
  361.  
  362. 0    value        OPERATION
  363. 0    value        SUBOPERATION
  364.  
  365. \ Some types of instruction need special treatment - e.g. AND etc. use the
  366. \ rA field for the destination.  So we define some types:
  367.  
  368. enum {    noType  loadStoreType  arithType  logicalType  cmpType  branchType  shiftType vecType  }
  369.  
  370.  
  371.  
  372. \        =================    UTILITY WORDS    ==================
  373.  
  374. : MONADIC?    \ ( opcode -- opcode b )
  375.     otNeg  otNot    within?  IF  true  EXIT  THEN
  376.     otFPmon otFPend    within?
  377. ;
  378.  
  379. : MEM_REFERENCING?    \ ( opcode -- b )
  380.     $ FF and
  381.     SELECT[    otFetch        ],
  382.           [ otStore        ]=>        true
  383.                   DEFAULT=>        drop false
  384.     ]SELECT
  385. ;
  386.     
  387.  
  388. PPC?
  389. [IF]
  390. : dasm  ;            \ can't disassemble in native mode yet!
  391. : z  ;
  392.  
  393. [ELSE]
  394.  
  395. forward dasm        \ disassembles what we've done so far
  396. forward dcurr        \ disassembles the current defn (even if not finished)
  397. forward Z            \ ends ppc compilation and disassembles.
  398.  
  399. [THEN]
  400.  
  401.  
  402. \ GetImmediateOp does the same when we're going to execute the operation
  403. \ now, returning the xt of the word to execute.
  404.  
  405. : GETIMMEDIATEOP  { opType subtype -- xt }
  406.     opType
  407.     SELECT[    otAdd    ]=>        ['] +
  408.           [    otSub    ]=>        ['] -
  409.           [    otAND    ]=>        ['] and
  410.           [    otOR    ]=>        ['] or
  411.           [    otXOR    ]=>        ['] xor
  412.           [    otMUL    ]=>        ['] *
  413.           [    otDIV    ]=>        ['] /
  414.           
  415.           [    otNEG    ]=>        ['] negate
  416.           [    otNOT    ]=>        ['] not
  417.  
  418.           [    otCMP    ]=>
  419.                   subtype
  420.                   CASE[ cmpNE    ]=>        ['] <>
  421.                     [ cmpEQ    ]=>        [']    =
  422.                     [ cmpGE    ]=>        ['] >=
  423.                     [ cmpLT    ]=>        ['] <
  424.                     [ cmpLE    ]=>        ['] <=
  425.                     [ cmpGT    ]=>        ['] >
  426.                     [ cmpZNE ]=>    ['] 0<>
  427.                     [ cmpZEQ ]=>    ['] 0=
  428.                     [ cmpZGE ]=>    ['] 0>=
  429.                     [ cmpZLT ]=>    ['] 0<
  430.                     [ cmpZLE ]=>    ['] 0<=
  431.                     [ cmpZGT ]=>    ['] 0>
  432.  
  433.                 DEFAULT=>    cr .h ."  undef otCMP subtype in getImmediateOp" 1 die
  434.                 ]CASE
  435.  
  436.           [    otUCMP    ]=>
  437.                   subtype
  438.                   CASE[ cmpHS    ]=>        ['] u>=
  439.                     [ cmpLO    ]=>        ['] u<
  440.                     [ cmpLS    ]=>        ['] u<=
  441.                     [ cmpHI    ]=>        ['] u>
  442.                 DEFAULT=>    cr .h ."  undef otUCMP subtype in getImmediateOp" 1 die
  443.                 ]CASE
  444.  
  445.           [    otShift    ]=>
  446.                   subtype
  447.                   CASE[ 0    ]=>        ['] <<
  448.                     [ 1    ]=>        ['] >>
  449.                     [ 3 ]=>        ['] a>>
  450.                 DEFAULT=>    cr .h ."  undef otShift subtype in getImmediateOp" 1 die
  451.                 ]CASE
  452.  
  453.         DEFAULT=>        cr .h ."  undef op passed to getImmediateOp" 1 die
  454.     ]SELECT
  455. ;
  456.  
  457. PPC? not
  458. [IF]        \ we put this in pnuc3 in target mode
  459.  
  460. \ 16bits? ( n signed? -- n b )
  461. \  returns true if n will fit in 16 bits (signed or unsigned as requested).
  462.  
  463. : 16BITS?    \ ( n signed? -- n b )
  464.     IF    -32768 32767  within?
  465.     ELSE
  466.         dup 16 >> 0=
  467.     THEN
  468. ;
  469.  
  470. [THEN]
  471.  
  472. : SIGNED?    \ ( operation - b )
  473.             \ Returns true if this is a signed op - assumed to be the
  474.             \  default.  We just return false for the specific unsigned
  475.             \  ops, and true for everything else.
  476.  
  477.     SELECT[    otUDIV    ],
  478.           [    otAND    ],
  479.           [    otOR    ],
  480.           [    otXOR    ],
  481.           [    otUCMP    ]=>        false
  482.         DEFAULT=>            drop  true
  483.     ]SELECT
  484. ;
  485.  
  486.  
  487. : REVERSE_COMPARISON    \ called if we swap operands of a compare.  Adjust 
  488.                         \  subOperation appropriately.
  489.  
  490.     subOperation $ 24 and  ?EXIT        \ out if monadic or EQ or NE
  491.     $ 10  xor> subOperation  ;
  492.  
  493.  
  494. \ This must come before we redefine @ABS below!
  495.  
  496. PPC? not
  497. [IF]
  498. from pasmMod import{    :PPC_code  ;PPC_code
  499.                         disasm  disasm_word  disasm_xt
  500.                         disasm_rng  disasm_cnt  disasm_one
  501.                         set_disasm_call_range  }
  502.  
  503. compile: pasmMod
  504.  
  505.  
  506. \ While still in 68k-land, we need a PPC-style reloc! and @abs.  The proper
  507. \  PPC versions will be compiled in pnuc3 and setup respectively.  Note,
  508. \  any changes must of course be made in both places.
  509.  
  510. : RELOC!  { theAddr dest -- }
  511.     theAddr addr>S&D
  512.     $ ffffff and  swap  24 <<  or
  513.     dest !
  514. ;
  515.  
  516.  
  517. : reloc,        DP    reloc!  4 ++> DP   ;
  518. : relocCode,    CDP reloc!  4 ++> CDP  ;
  519. : displCode,    CDP displ!    4 ++> CDP  ;
  520.  
  521.  
  522. \ In the target compilation, we only have 4 segments.
  523.  
  524. : @ABS  { addr \ relocAddr seg# displ -- absAddr }
  525.     addr @  -> relocAddr
  526.     relocAddr  $ ffffff and  -> displ
  527.     relocAddr  24 >>  -> seg#
  528.     seg#
  529.     SELECT[    8    ]=>        code_start
  530.           [    9    ]=>        data_start
  531.           [    10    ]=>        seg_code_start
  532.           [    11    ]=>        seg_data_start
  533.     DEFAULT=>    ." not a reloc addr" 1 die
  534.     ]SELECT
  535.     displ +
  536. ;
  537.  
  538.  
  539. : @abs6        @abs  ;            \ a variant name we can call later when @abs
  540.                             \  has been redefined in the PPC image
  541.  
  542. [THEN]
  543.  
  544.  
  545. endload
  546.  
  547.  
  548.  
  549.  
  550.                         =======================
  551.                         TECHNICAL DOCUMENTATION
  552.                         =======================
  553.  
  554. Here we describe all the nuts and bolts stuff relating to PPC code
  555. generation.  We've collected together a whole lot of commentary from
  556. all over our source files -- it should be easier to find things if
  557. they're all in one place, and we can also cut and paste it into the
  558. manual.
  559.  
  560.  
  561.  
  562. The general way to generate optimized code for an architecture with n
  563. registers is to analyse each basic block and generate a directed acyclic
  564. graph (DAG) whose nodes represent each value generated and whose edges
  565. represent uses of those values.  Note it isn't a tree, since more than
  566. one edge can go into a node.  Then optimization can be done, and common
  567. subexpressions (i.e. nodes) combined.
  568.  
  569. Then, using graph coloring or whatever, the nodes are assigned to
  570. registers.  This assumes there are less regs than nodes, so that we
  571. have to find all dependencies, and re-use a reg when its old value
  572. isn't needed any more.
  573.  
  574. Here we can simplify things a little, and manage everything in one pass.
  575. On the PPC we have so many regs that for normal shortish basic blocks,
  576. we will generally be able to simply assign a different reg for each node.
  577. On the few occasions when we don't have a free reg, we can select one
  578. which has a value with no outstanding references - there's a slight chance
  579. we could have used this value in a subsequent op, but this is pretty well
  580. negligible.  We can optimize on the fly: each time we get a new value,
  581. we can search the reg set for a match so we can use a combined node.
  582.  
  583. This code is invoked as follows:
  584. Whenever Handlers is called to generate 68K code, if PPC? is true,
  585. the Handlers selector and opcode is pushed and PPCvec is executed.
  586. We will set PPCvec to point to PPC_compile which will use the selector
  587. to dispatch to the right routine.
  588.  
  589.  
  590.         =============    MEMORY ARCHITECTURE    ================
  591.  
  592. On the PPC, code and data is normally kept separate, with the code
  593. being read-only.  The PEF format defines separate code and data sections,
  594. and at launch time these are placed in pointer-based blocks in memory.
  595. We ought to conform to this convention for installed apps, since it will
  596. give the best performance.
  597.  
  598. In the development environment, our dictionary should be in a read-write
  599. block for obvious reasons.  We'll define a separate data area, which
  600. will become the data section of an installed app.  These two areas
  601. can be in handles, which will allow us to resize them on the fly if
  602. necessary.
  603.  
  604. At installation time, we'll generate a PEF in which the dictionary is
  605. added to the existing code section, and the data area is added to the
  606. data section.  Our initial nucleus will probably be generated exactly
  607. this way, either from the 68k or PPC version.  Thus our initial
  608. nucleus is simply an application, which transforms itself into the
  609. Mops development environment by creating a handle for the new dictionary
  610. and data areas.  Now, we could allow the new dictionary area to link
  611. itself to the old one by some cleverness, but since the dic would
  612. only be getting split at one place I don't think it would be worth
  613. the complexity.  Better to just BlockMove the old dic area to the start
  614. of the new when the dev environment is being set up, and likewise for
  615. the data area.
  616.  
  617. Colon uses a new header format incorporating two flag bytes in addition to
  618. what we use on the 68k, and also has to observe 4-byte alignment for the
  619. code.  For this reason we generate a full PPC-style header (including 4-byte
  620. alignment) for colon definitions.  When we compile a call to a colon defn we
  621. have to do PPC-style alignment even on the 68k.  For other types of definition
  622. we don't have to bother, and the code should work on both platforms (since
  623. on the PPC FIND will look after the extra alignment).
  624.  
  625.  
  626.         =============    REGISTER DEFINITIONS:    ================
  627.  
  628. We need 3 regs for scratch in boilerplate code sequences.  We'll use
  629. r0, which is a bit unusual anyway, and r11 and r12 (see below).
  630.  
  631. r1 is the stack pointer, r2 is RTOC.  We can't monkey with these.
  632. r11 and r12 are used in the calling sequence for external calls.  Apple
  633. says they can be used as scratch at all other times, so we'll use them
  634. in boilerplate sequences.  PowerMacForth does this too, and in the assembler
  635. they're aliased as rX and rY.
  636.  
  637. For external calls, r3-r10 are used for parameters, and r3 for a returned
  638. result.  They won't be saved over the calls.  Of course for internal Mops
  639. calls we can do what we like.  We can use these regs for general operands,
  640. and on an external call normalize the stack so that the required number of
  641. cells are stored in r3 on.  At that stage we won't have any other cached
  642. stack cells, so we don't need the regs preserved anyway.
  643.  
  644. This scenario gives us 8 regs for general operands, i.e. cached stack
  645. cells (r3-r10), which should be enough.  If it turns out not to be enough
  646. we could grab a couple of the regs we've allocated for locals (see below).
  647.  
  648. r13-31 are "non-volatile" - they're saved over external calls.  For
  649. internal Mops calls we just need to save the locals, since other regs
  650. like the base address regs don't get changed.
  651.  
  652. Now for the special regs we need.  These all need to be saved over external
  653. calls, and so are in the non-volatile block.
  654.  
  655. For addressing the dictionary, a difference to the 68k version is that
  656. we need to keep code and data separate (see above).  In the development
  657. environment these will be in handle-based blocks, and in an installed
  658. app they'll be defined in the PEF which will make them end up in pointer-
  659. based blocks.  Anyway, as long as we handle the addressability questions
  660. properly, it shouldn't matter where they are.
  661.  
  662. Code references will be for branches, constants and other constant data
  663. like literal strings and class info.
  664.  
  665. Constants can always be handled via literal instructions.  Even if it
  666. needs more than 16 bits it can be generated in a reg with 2 instructions
  667. which will be faster than a memory reference.
  668.  
  669. Branches will always be self-relative, and they have enough displacement
  670. bits to get us anywhere. 
  671.  
  672. For other constant data, however, it's extremely handy to have a base
  673. reg available, even if these references aren't performance-critical.
  674.  
  675. Thus, if we still have modules (which is still up for grabs), we'll
  676. need 4 base regs - 2 to address code and 2 for data.  Note that on
  677. entry, r2 (RTOC) always points to the start of the data area as defined
  678. in the PEF.  But we can't use RTOC as a regular base reg, since in the
  679. dev environment our data area will be off in a separate handle.
  680.  
  681. Other regs we need are RP (return stack pointer), the loop variable I,
  682. and the base address of the current object.  Now we may as well use one of
  683. our "local" registers for I, since it will be very rare for us to need
  684. all of them.  This will mean one less local in definitions that use I,
  685. but that's not a problem.
  686.  
  687. It seems we should go for a separate FP stack, since the Scientific
  688. Library is now using this.  This will also give better code on the PPC, since
  689. when we bring stack cells back from mem to regs, we'll always know which regs
  690. to move them to.  The floating stack pointer probably should be in a
  691. register.
  692.  
  693. So in all we'll need 7 special regs out of the non-volatile block.
  694.  
  695. This leaves r19-r31 for locals, which means that if we limit the number
  696. of locals to 13, we can keep them all in registers.  This looks reasonable.
  697.  
  698.  
  699. Some notes on register handling across internal Mops calls:
  700. Saving and restoring local regs can be a bit long-winded, so to save
  701. space we should normally do what we do on the 68k - that is, at the
  702. start of each defn, save whatever regs we need for locals, and restore
  703. them at the end.  For EXIT, instead of doing everything inline as we
  704. did on the 68k, we'll do a branch to the semicolon.  This is almost as
  705. fast (esp. as it's an unconditional branch), and saves space.
  706.  
  707. We'll probably make an exception for leaf procs, since these get executed
  708. so frequently.  What I'm currently planning, in the case where the leaf
  709. proc has named parms/locals, is to do the houskeeping in the calling
  710. routine instead of in the called leaf proc.  This will give me the
  711. possibility of generating the parms straight in the required regs.
  712. Also I might be able to do the saving and restoring of the needed regs
  713. at the beginning and end of the calling routine (depending on what
  714. parms/locals that routine might need.  This would get these housekeeping
  715. operations out of any inner loops.
  716.  
  717. This alternative calling convention should certainly be faster, but will
  718. take a lot more space, so I won't do it all the time.
  719.  
  720.  
  721.  
  722.  
  723.  
  724. The 2 flag bytes are organized as 4 nybbles:
  725.  
  726. nybble 0:    bit 0:    1 if it's a leaf defn
  727.             bit 1:    1 if it alters the count register
  728.             bit 2:    spare
  729.             bit 3:    1 if it alters the FP or vector regs.
  730.  
  731. nybble 1:    number of results in registers on exit
  732. nybble 2:    number of named parameters
  733. nybble 3:    number of named parms + locals
  734.                 (doing it this way is a bit more convenient, and the
  735.                  max number of parms+locals is only 11, so we have
  736.                  enough bits)
  737.  
  738. If the definition does any floating point or AltiVec operations, or 
  739. anything that alters the FP or vector registers, we need more flags, 
  740. so we add an extra 32 bits.  For alignment, we have to take at least 
  741. 32, so we might as well make the most of it.
  742.  
  743. byte 0:        $ BB - this is basically just for the disassembler.
  744. byte 1:        (if we end up with a vector stack, we might
  745.              use bytes 0 and 1 as 4 nybbles as for floats.)
  746.  
  747. bytes 2 and 3 are 4 nybbles:
  748.  
  749. nybble 0:
  750. nybble 1:    number of floating results in registers on exit
  751. nybble 2:    number of named floating parameters
  752. nybble 3:    number of named floating parms + locals
  753.  
  754.  
  755.  
  756.     =============== FINALIZATION OF DEFINITIONS =================
  757.  
  758. At semicolon time, there are a number of things we have to fix up in
  759. the definition we just compiled.  Once we've compiled the prolog and
  760. epilog and added the const_data, if any, the final location of the 
  761. code is known.  We can then "finalize" the definition.  This includes
  762. resolving any EXITs and LEAVEs and putting in the correct offsets for
  763. calls to other words (these couldn't be determined before the code's
  764. final location was determined).
  765.  
  766. To handle these various things, we use some pseudo-instructions to stand in
  767. place of the final instructions we're going to put in those same locations
  768. at finalization time.  To finalize, we look through the whole definition
  769. for these pseudo-instructions, and take the appropriate action.
  770.  
  771. For the pseudo-instructions, we have to use opcodes that can't ever be
  772. used for real instructions.  Now we'll never use the lmw and stmw 
  773. instructions, since Keith D has warned me that they'll go away in
  774. future!  This means that we can use their values as pseudo-opcodes,
  775. since we know that Mops will never generate them with their proper
  776. meaning.
  777.  
  778. The values in question are primary opcodes 46 and 47, which means
  779. $B8xxxxxx to $BFxxxxxx.  We also define our handler codes into this
  780. same range, since the two-byte handler code appears on an aligned
  781. boundary.  This will prevent a handler code ever being mistaken for an
  782. instruction.  Thus all our handler codes and pseudo-instructions
  783. identify themselves, which generally makes life easier.
  784.  
  785. So far we've defined these:
  786.  
  787. BAxx xxxx    call to a Mops word (xx xxxx is code-relative offset)
  788.  
  789. BBxx xxxx    floating-point/AltiVec flag bytes.  This code is basically 
  790.             for the disassembler, since it's aligned and 3 flag bytes
  791.                   are plenty.  It shouldn't come up in finalization.
  792.  
  793. BCxx        all handler codes which have no boilerplate code (can't
  794.             be EXECUTEd).  Unlike on the 68k, xx is unsigned and not
  795.             doubled (so we can have 256 codes if we need them).
  796.             
  797. BDxx        all other handler codes, except for colon defns.  They can
  798.                   be EXECUTEd.
  799.  
  800. BE00            handler code for a colon defn
  801. BE01            ditto, but means this is a forward defn.
  802. BE02            marks the start of :loc code
  803. BE03            marks the start of :mloc code
  804. BE04            handler code for a :ppc_proc defn
  805. BE05            handler code for :entry
  806.  
  807. BE40            method (note BD40 is an inline method - so the 40 always
  808.                       marks a method)
  809.  
  810.         (we'll reserve BExx for any further options on colon definitions.)
  811.   
  812. These next two can't ever appear inside a definition, so we give an error
  813. if they're encountered during finalization.
  814.  
  815. BF01        handler code for SYSCALL and EXTERN
  816. BF0B        handler code for LIBRARY
  817. BF0C 0000    case-sensitive name for :ENTRY follows
  818.  
  819. BF02 0000    EXIT
  820. BF03 xxxx    conditional EXIT (xxxx is cond. branch opcode)
  821. BF04 0000    LEAVE
  822. BF05 0000    LOOP
  823. BF06 0000    target of a forward defn.  This marker is redundant,
  824.                 but makes the decompiler output look more sensible.
  825.  
  826. BF08 xxxx    unconditional branch.  xxxx is offset (we only need 16 bits).
  827.  
  828. BF09 xxxx    ELSE - branch.  xxxx is initially the offset back to the
  829.                   original conditional branch, in case we delete this branch
  830.                   and need to adjust.  Once the branch is resolved, and we
  831.                   know it won't be deleted, xxxx becomes the branch offset
  832.                   as for other unconditional branches.  We can tell which
  833.                   is which, since the first offset is negative and the
  834.                   second positive.
  835.  
  836. BF0A        replace with a literal load into r0 of the distance the code
  837.                   is moved.  Used in generating the addr of a location 
  838.                   within the current definition (since we don't know until
  839.                   the end how far it might be moved).
  840.  
  841.  
  842.  
  843.         ==================== EXTERNAL CALLS ======================
  844.  
  845.  
  846. CALL_EXTERN handles an external call.  This requires that we set things up as
  847.     the PowerPC volume of IM says:
  848.  
  849. 1.    We have a pointer which is resolved by the CFM - this will
  850.     be the address of a transition vector.  This pointer will be in the
  851.     data area (since it gets changed), and has a reloc addr pointing
  852.     to it in the code area, which belongs to the SYSCALL or EXTERN
  853.     word.
  854.     
  855.     We have to allow for new external calls to be asked for, then
  856.     executed straight away, so we use a scheme where when we do an
  857.     external call, we check whether the pointer has been resolved
  858.     yet, and resolve it if it hasn't.  We can easily tell, since we
  859.     initialize each pointer to nilP, which is an illegal address.
  860.     This test and the call to FindSymbol to resolve it, is in
  861.     get_transition_vector which is called at the beginning of our
  862.     external call sequence.
  863.     
  864.     We could save a couple of instructions by pre-resolving symbols that
  865.     are already in the dictionary image, but it's not worth it - it's 
  866.     better to use just one scheme, and we do need to be able to resolve
  867.     on demand, so that's the way we do it.
  868.  
  869.     The transition vector has 2 addresses - the addr for us to branch to,
  870.     and the new RTOC value.  The dest addr has to be loaded into the CTR
  871.     or the LR for us to use it as a branch target.  We use the CTR - see
  872.     below for the reason for this.  We want to load the dest addr as early
  873.     as possible so that instruction fetching won't stall, so we do this
  874.     part of the setup before we equalize the stack - during the equalization
  875.     nothing needs the CTR anyway.
  876.     
  877.     We use r12 for the addr of the transition vector itself, as IM says.
  878.     This also won't get messed with during equalization.
  879.     
  880.     We set up r12 and the CTR in get_transition_vector, as well as resolving
  881.     the symbol as described above.  Factoring as much as possible into
  882.     get_transition_vector saves code space in the call sequence for
  883.     external calls.
  884.     
  885.     So, as well as a bit of housekeeping, the main thing that CALL_EXTERN
  886.     does is to compile a call to get_transition_vector.  CALL_EXTERN then
  887.     passes 1 as an "xt" to CALL_H.  1 can never be a real xt, since they must
  888.     be even, so this tells call_h that this is an external call.  CALL_H
  889.     looks after everything from here on, including the stack equalization.
  890.  
  891.  
  892. 2.  The first thing call_h does is pass 1 to EQUALIZE_FOR_CALL (in the
  893.     equalization section).  This gets the parameters into the right regs (and
  894.     the parameter area, if necessary), as needed for external calls.
  895.  
  896.     IM envisages that setting the SP is already done by the prolog
  897.     of the current routine, on behalf of all external calls that this
  898.     routine makes.  The parameter area is big enough for the call with the
  899.     most parameters, and the others leave some unused space below the parm
  900.     area (actually higher in memory).  The parm area for each call must come
  901.     immediately below the linkage area, so the callee can find it.
  902.     
  903.     But in Mops we have a separate data stack pointer, so we simply
  904.     set up a linkage area for external calls using the system SP (gpr1) at
  905.     startup time, and never change it after that.
  906.  
  907. 3.    call_h then calls COMPILE_EXTERN_CALL (in this file, below) to compile 
  908.     the actual call.  To do this, we store our own RTOC into the linkage area
  909.     (actually this is done once and for all at startup since we have a 
  910.     permanent frame for external calls),    and load RTOC from the transition 
  911.     vector (still pointed to by r12).  We then bctrl (branch and link to count 
  912.     register) to call the external code.  (We could equally well have used 
  913.     the LR - see below.)
  914.  
  915.  
  916. Note: the standard sequence for cross-TOC calls in Metrowerks C is as
  917. follows.  We do much the same, but in a different order - in particular
  918. we grab the dest addr and get it into the CTR as early as possible, before
  919. we normalize the stack etc., and we move the SP to allocate the parm and
  920. linkage areas on each call.
  921.  
  922. We could equally well have used the LR instead of the CTR.  MW have to use
  923. the CTR since they've done a bl to the out-of-line code, and have to preserve
  924. the LR.  But the IBM manual recommends using the CTR for computed branches
  925. like this, to make life easier for debuggers etc, so that's what we'll do.
  926.  
  927. inline:
  928.         bl        xxx
  929.         lwz        r2/TOC, $14(r1/SP)
  930.         ...
  931.     
  932.  
  933. xxx        lwz        r12, <offs>(r2/TOC)    / TOC entry is a pointer to transfer vector
  934.         stw        r2/TOC, $14(r1/SP)    / Save RTOC
  935.         lwz        r0, (r12)            / 1st entry in TV is destination addr
  936.         lwz        r2/TOC, $4(r12)        / 2nd entry is new TOC addr - put in RTOC
  937.         mtspr    CTR, r0                / dest addr to CTR
  938.         bctr                        / branch there
  939.  
  940.  
  941.  
  942.  
  943.  
  944. ===================  CLASS/OBJECT FORMATS ======================
  945.  
  946.  
  947.         =============== Object header ====================
  948.  
  949. Note if the obj is an ivar, it doesn't have a header if it's in a record,
  950. unless the ivar is indexed.  Indexed ivars always have headers, no matter
  951. what, since the indexing code relies on it.
  952.  
  953. PPC notes: we have to make some minor changes to the object header format
  954. for various reasons.
  955.  
  956. 1. As objects live in the data area, we need a back pointer to the dic
  957. entry in the code area, so methods like .ID: work.
  958.  
  959. 2. The class pointer is a 4-byte relocatable address, and we want it to
  960. be aligned.
  961.  
  962. 3. The indexed length of the object now always occupies the 4 bytes at
  963. the end of the indexed descriptor, whereas on the 68k, although we
  964. allocated 4 bytes, we normally only took notice of the low 2 bytes.
  965. We want the 4 bytes preceding the obj's data to look like a negative
  966. indexed length if the object isn't indexed.
  967.  
  968. So we end up with this layout:
  969.  
  970. 4 bytes        Back pointer to cfa of obj's dic entry (relocatable).
  971.             Zero if no dic entry, or if no name field there.
  972.  
  973. 4 bytes        Class pointer (relocatable).
  974.  
  975. 2 bytes        Self relative offset to the class pointer.
  976.             For simple objects (i.e. not embedded), this is -4.
  977.             For embedded objects, it will be more negative.  Note it
  978.             will always be negative.
  979.  
  980. 2 bytes        Self relative offset to the indexed area.  If not indexed,
  981.             this will be 2, pointing to the next byte which is the first
  982.             data byte of the object.  This means, if we erroneously try
  983.             to access the indexed area of a non-indexed object, we'll
  984.             get sent to the non-indexed data area, and try to interpret
  985.             the preceding 4 bytes as an "indexed length" (which is what
  986.             precedes a valid indexed area).  But these 4 bytes are these
  987.             two offsets, which will always appear as a negative number.
  988.             If we're doing range checking, this will always trap.
  989.             We did a similar sneaky trick on the 68k, but the field
  990.             lengths/positions were different.
  991.  
  992. (object's data starts here)
  993.  
  994. This format means that when multiply inheriting, we need 4 bytes
  995. separating each group of ivars ("embedded object"), not 2 as on
  996. the 68k.
  997.  
  998.  
  999. For indexed objects, the indexed area (after the ivars) is preceded by
  1000. the indexed descriptor (xdesc) with the following format.  This format
  1001. is the same as on the 68k, except that it starts off-aligned, i.e.
  1002. the #elements field is 4-byte aligned.
  1003.  
  1004. 2 bytes        Width of indexed elements (in bytes)
  1005. 4 bytes        Number of elements minus 1 (i.e. LIMIT-1).
  1006.             We can check this with a trap instruction.
  1007.  
  1008.  
  1009.  
  1010.         ==============  Class dictionary entry  ================
  1011.  
  1012. link/name/hndlr    as for normal words - normal class hndlr is $BC1D,
  1013. and for imported classes, $BC2D.
  1014.  
  1015. Note that the offsets are defined in 2 places, which must agree! -
  1016. here, and in pNuc4.
  1017.  
  1018. 2 bytes            flags
  1019. (note - we're now aligned)
  1020.  
  1021. (offs 2)    32 bytes    links to 8-way hashed method chains (relative)
  1022. (offs 34)    4 bytes        link to ivar chain (relative)
  1023. (offs 38)    2 bytes        padding for alignment of the n-way, and to put
  1024.                         the next fields in the same place as on the 68k,
  1025.                         which simplifies (findM).
  1026. (offs 40)    2 bytes        non-indexed data length
  1027. (offs 42)    2 bytes        width of indexed elements, or zero if not indexed
  1028. (offs 44)    2 bytes        "xdispl offs" - the ivar offset where indexing starts
  1029.                         (used by large_obj_arrays), or zero if none.
  1030. (offs 46)    4(n+1) bytes
  1031.                 n-way to superclasses (n relocatable addrs terminated by zero)
  1032.  
  1033. Flag bits:
  1034.     $0001        "large" - indexed with > 64K elements.
  1035.     $0002        class is exported from a module
  1036.     $0004        class is general
  1037.  
  1038.     $00X0        if nonzero, an object of this class could go
  1039.                 in a register:
  1040.                     3    gpr
  1041.                     4    fpr
  1042.                     5    vector
  1043.  
  1044.     $0n00        data must be aligned by 2**n.  If zero, we use the
  1045.                  normal default alignment.  (So far we only use this
  1046.                  for vectors, which must be 16-byte aligned.)
  1047.  
  1048.     $8000        class is META (we use this to terminate NW_IVsetup)
  1049.  
  1050. Note: on the 68k, at the class cfa there was a call to BLD, the word
  1051. which built an object.  These 4 bytes also served as a unique marker
  1052. identifying a class dic entry, since we did a JSR to BLD, and this
  1053. always had the same bit pattern.  We treated the class handler code
  1054. the same as for a colon definition, and simply BSR'd to the cfa.
  1055.  
  1056. On the PPC we'll really use class_h, so that a class won't
  1057. look like a colon definition any more.  This is a bit more logical
  1058. and shouldn't cause any problems.  In any case, we couldn't use a
  1059. call to BLD as a unique marker, since calls are all self-relative
  1060. on the PPC so that calls to any particular word will have a different
  1061. bit pattern depending on where they are.
  1062.  
  1063. class_h is $BC1D, and will give an error if we try to EXECUTE a class
  1064. (as with all $BCxx codes).  I doubt this will break any existing code.
  1065.  
  1066. Note also we've moved the "flags" from after the indexed width item,
  1067. up to be the first item.  This is so the 4-byte items come out aligned
  1068. without sundry padding.
  1069.  
  1070.  
  1071.         ==============  ivar dictionary entry  ================
  1072.  
  1073. \ note: this format is the same on the PPC and 68k, for once!
  1074.  
  1075. 4 bytes        hashed name
  1076. 4 bytes        link to prev ivar dic entry (self-relative addr)
  1077. 4 bytes        class pointer (relocatable)
  1078. 2 bytes        offset of this ivar's data from the base addr of the class
  1079. 2 bytes        number of elements if indexed, or zero if not
  1080. 2 bytes        flags
  1081.  
  1082. Flag bits:
  1083.  
  1084.     $0001    ivar gets an object header
  1085.     $0002    this is a static ivar
  1086.     $0004    this is a public ivar
  1087.     $XXX0    this ivar is in a register (it's actually a temp object).
  1088.             Reg bits are as for class flags above, in the lo 4 bits,
  1089.             and the actual reg number in the next 5 bits.  So far
  1090.             the hi 3 bits are free (zero).
  1091.  
  1092. Note: although indexed objects can have 2^^32 elements, we are
  1093. assuming that an ivar can't have more than 64K elements.  This is
  1094. because we are limiting the maximum ivar length of a class to 64K bytes,
  1095. which is a stricter condition.  Would anybody want a longer ivar than
  1096. this??
  1097.  
  1098.         ==============  Method dictionary entry  ================
  1099.  
  1100. 4 bytes        hashed name
  1101. 4 bytes        link to prev method dic entry (self-relative addr)
  1102. 2 bytes        method flags
  1103. 2 bytes        0 (alignment)
  1104. 2 bytes        $BE40 - "handler code" - not actually used as a handler, but
  1105.             marks this as a method for decompiler etc.  Note that an
  1106.             inline method uses the code BD40, so I can just look for
  1107.             40 in the low byte to see if it's a method.
  1108. 2 bytes        flag bytes as for colon defns, giving number of named parms etc.
  1109.             This is the method's cfa (xt) here.
  1110.  
  1111.     (method code follows)
  1112.  
  1113.  
  1114. Method flag bits:
  1115.  
  1116.     $0001    private method (note other way round to ivars - we're using
  1117.             1 for the unusual case)
  1118.     $0080    there's a callFirst and/or callLast method
  1119.  
  1120. Note that the method code starts 6 bytes later than in the 68k version.
  1121.  
  1122.  
  1123.         ==========================================================
  1124. *)
  1125.